#import "GnuView.h"


@implementation GnuView

static NXCoord xsize= NEXT_XMAX/10+50;
static NXCoord ysize= NEXT_YMAX/10+50;

static int printing;
static void setprintsize();

char empty[]="";

- initFrame: (NXRect *)rects
{
    [super initFrame:rects];
		
	PSstring = empty;
	[self display];

	return self;
}


	/* This is here to fix NeXT bug # 21973:  failure to free D.O. memory */
	/* Note:  personally I don't think this fixes it. */
- free
{
	free(PSstring);
	[super free];
	
	return self;

}

- executePS:(char *) PStext
{
	
	PSstring = PStext;

	[window makeKeyAndOrderFront:self];
	[self display];

	return self;
}


- drawSelf:(const NXRect *) rects : (int) rectCount
{
    DPSContext d;
	
    d = DPSGetCurrentContext();

	if (!printing) {
							/* Clear Screen */ 
		PSsetgray(NX_WHITE);
		NXRectFill(&bounds);
							/* scale to gnuplot coords */
		[self setDrawSize:xsize:ysize];	
	}
	else {
		setprintsize();
	}

	DPSWritePostScript(d, PSstring, strlen(PSstring));

    DPSFlushContext(d);

	return self;
}


- printPSCode: sender
{
	printing = 1;
	[super printPSCode:sender];
	printing = 0;
	
	return self;
}

static void setprintsize()
{
	DPSContext d;
	NXRect *paperRect;
	float width, height;
	id prInfo;

    d = DPSGetCurrentContext();
	prInfo = [NXApp printInfo];
	paperRect = (NXRect *) [prInfo paperRect];
	
	width = paperRect->size.width;
	height = paperRect->size.height;

	DPSPrintf(d, "grestore\ngrestore\ngrestore\n");
	
	if ([prInfo orientation] == NX_LANDSCAPE) {		
		DPSPrintf(d, "-90 rotate\n");
		DPSPrintf(d, "%g 0 translate\n", -1.0 * paperRect->size.width);
		DPSPrintf(d, "0 %g translate\n", paperRect->size.height/20);
	}
	else 
	{					
		DPSPrintf(d, "%g %g scale\n", width/height, height/width);	
	}
		
	DPSPrintf(d, "gsave\ngsave\n");

    DPSFlushContext(d);

	return;
}




@end


